--- 恒瑞RS485水位传感器, dtype(11)
module(..., package.seeall)

local logtag = "HR8XXX"
local read_interval = 5000
local cid, uid = 3, 3 -- 默认用3通道
local dtu, udtu = {}, {} -- 配置文件
local read_command = '010300010005D409'

function setDtu(dtup, udtup)
    dtu, udtu = dtup, udtup
    -- 如果设置是本协议
    if udtu and tonumber(udtu.dtype) == 11 then sys.taskInit(init) end
end
local function process(data)
    if #data > 10 then
        local val, v_hex = {}
        v_hex = data:sub(4, 7):toHex()
        val.waterLevel = tonumber(v_hex, 16) / 1000
        v_hex = data:sub(8, 9):toHex()
        val.waterTemp = tonumber(v_hex, 16) / 10
        usrdata.update({val.waterLevel,val.waterTemp})
        lcd.LCD_DATA[3] = 'L:' .. (val.waterLevel or 'ERROR') .. "m T:" .. (val.waterTemp or 'ERROR')
    end
end
function init()
    sys.wait(1000)
    power.openBoost()
    sys.wait(3000) -- 等待传感器稳定
    -- 测试 埋深1001 水温22.8
    --process(("01030a 000003e9 00e4 000000590d9a"):fromHex())
    while true do
        -- 读取数据
        sys.publish("UART_SENT_RDY_" .. uid, uid, read_command:fromHex())
        log.warn(logtag, "间隔5秒等待串口数据")
        result, data = sys.waitUntil('UART_READ_DONE_NEXT_' .. uid, read_interval)
        if result then
            if (data) then
                process(data)
            end
            sys.wait(read_interval)
        else
            lcd.LCD_DATA[3] = string.format("U%dD%d READ TIMEOUT",uid,udtu.dtype)
        end
    end

end
